package com.novabluetooth.services.ktxyj;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import com.health.NovaApplication;
import com.health.R;
import com.health.tablebean.BTDevice;
import com.health.tablebean.SBCL_DATA;
import com.novabluetooth.adapter.XueYaAdapter;
import com.novabluetooth.adapter.XueYangAdapter;
import com.novabluetooth.services.BluetoothConstant;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("NewApi")
public class KTXYJActivity extends Activity implements ICallBack {
	static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
	Button btnSearch, btnExit, btn_up, btnXueYang;
	ListView lv_list;
	BluetoothAdapter btAdapt;
	private BluetoothChatService mChatService;
	public static BluetoothSocket btSocket;
	String mDeviceAddress;
	String mDeviceName;
	// 康泰08A血压计
	public final static String TJ_KANGTAIXUEYA = BluetoothConstant.XUEYA_CONTEC08A1_KTXYJ;
	private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	XueYaAdapter xy;
	XueYangAdapter xYang;

	private TextView title;
	// public ArrayList<DeviceData> deviceDataList = new
	// ArrayList<DeviceData>();
	String IDCARD;// 身份证号

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		if (mChatService == null)
			setupChat();

	}

	private CallBack call;

	private void setupChat() {
		// TODO Auto-generated method stub
		mChatService = new BluetoothChatService(this, call);
	}

	@SuppressLint("NewApi")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.sbcl_ktxyj);
		// Intent service = new Intent(getApplicationContext(),
		// NoticeService_XY.class);
		// startService(service);
		if(NovaApplication.getUserInfo()!=null){
			IDCARD = NovaApplication.getUserInfo().getIDCARD();
			if (TextUtils.isEmpty(IDCARD)) {
				return;
			}
		}
		
		call = new CallBack(this.m_mtbuf, this);
		// Button 设置
		btnSearch = (Button) this.findViewById(R.id.start_cl);
		btnSearch.setOnClickListener(new ClickEvent());
		btnXueYang = (Button) this.findViewById(R.id.start_cl_xueyang);
		btnXueYang.setOnClickListener(new ClickEvent());
		btnExit = (Button) this.findViewById(R.id.btn_back);
		btnExit.setOnClickListener(new ClickEvent());

		title = (TextView) this.findViewById(R.id.title);
		title.setText("康泰血压计");
		btn_up = (Button) this.findViewById(R.id.btn_up);
		btn_up.setVisibility(View.GONE);
		lv_list = (ListView) this.findViewById(R.id.lv_list);
		// int size=DeviceData.m_deviceDataList.size();
		// if(size>0){
		// DeviceData data = DeviceData.m_deviceDataList.get(size-1);
		// deviceDataList.add(data);
		// }
		btAdapt = BluetoothAdapter.getDefaultAdapter();// 初始化本机蓝牙功能

		if (btAdapt.getState() == BluetoothAdapter.STATE_OFF) {
			// 读取蓝牙状态并显示
			btAdapt.enable();
		}

		// 注册Receiver来获取蓝牙设备相关的结果
		IntentFilter intent = new IntentFilter();
		intent.addAction(BluetoothDevice.ACTION_FOUND);// 用BroadcastReceiver来取得搜索结果
		intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
		intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
		intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
		intent.addAction(BluetoothChatService.ACTION_DATA_AVAILABLE);
		registerReceiver(searchDevices, intent);
	}

	private BroadcastReceiver searchDevices = new BroadcastReceiver() {

		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (intent.getExtras() != null) {
				Bundle b = intent.getExtras();
				Object[] lstName = b.keySet().toArray();

				// 显示所有收到的消息及其细节
				for (int i = 0; i < lstName.length; i++) {
					String keyName = lstName[i].toString();
					Log.e(keyName, String.valueOf(b.get(keyName)));
				}
			}
			// 搜索设备时，取得设备的MAC地址
			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
				BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				if (device.getName() == null) {
					return;
				}
				if (device.getName().contains("NIBP03") || device.getName().equals(Constants.DEVICE_NAME2)) {
					Log.e("---------", "-----------");

					List<BTDevice> btDevices = NovaApplication.fdbmanger.findAllBTByWhere(BTDevice.class,
							"macAddress = " + "'" + device.getAddress() + "'");
					if (btDevices.size() > 0) {
						if (mChatService != null)
							mChatService.stop();
						try {
							Thread.sleep(2000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						mChatService.start();
						mChatService.connect(device);
					}
				}
			} else if (BluetoothChatService.ACTION_DATA_AVAILABLE.equals(action)) {
				// String data =
				// intent.getStringExtra(TJBluetoothLeService.EXTRA_DATA);
				// // TODO 完成对数据的显示
				call();
			}
		}
	};
	public MtBuf m_mtbuf = new MtBuf(KTXYJActivity.this);

	@Override
	protected void onDestroy() {

		super.onDestroy();
		this.unregisterReceiver(searchDevices);
		if (mChatService != null) {
			mChatService.stop();
		}

	}

	class ClickEvent implements View.OnClickListener {
		public void onClick(View v) {
			if (v == btnSearch)// 搜索蓝牙设备，在BroadcastReceiver显示结果
			{
				if (btAdapt.getState() == BluetoothAdapter.STATE_OFF) {// 如果蓝牙还没开启
					Toast.makeText(KTXYJActivity.this, "请先打开蓝牙", 1000).show();
					return;
				}
				// setTitle("本机蓝牙地址：" + btAdapt.getAddress());
				btAdapt.startDiscovery();
				btnSearch.setEnabled(false);
				NovaApplication.isXueYa = true;

			} else if (v == btnExit) {
				try {
					if (btSocket != null)
						btSocket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				KTXYJActivity.this.finish();
			} else if (v == btnXueYang) {
				if (btAdapt.getState() == BluetoothAdapter.STATE_OFF) {// 如果蓝牙还没开启
					Toast.makeText(KTXYJActivity.this, "请先打开蓝牙", 1000).show();
					return;
				}
				// setTitle("本机蓝牙地址：" + btAdapt.getAddress());
				btAdapt.startDiscovery();
				btnXueYang.setEnabled(false);
				NovaApplication.isXueYa = false;

			}
		}

	}

	public int[] m_buf = new int[0];

	public void call() {
		// Vector<Integer> _ver = MtBuf.m_buf;
		// for (int i = 0; i < _ver.size(); i++) {
		// Log.i("............", Integer.toHexString(_ver.get(i) & 0xFF));
		//
		// }
		btnSearch.setEnabled(true);
		btnXueYang.setEnabled(true);
		// DeviceData.printDatas();
		if (NovaApplication.isXueYa) {
			int size = DeviceData.m_deviceDataList.size();
			System.out.println("血压记录条数：" + size);
			if (size > 0) {
				DeviceData _DeviceData = DeviceData.m_deviceDataList.get(size - 1);
				List<DeviceData> listXueYa = new ArrayList<DeviceData>();
				listXueYa.add(_DeviceData);
				xy = new XueYaAdapter(KTXYJActivity.this, listXueYa);
				lv_list.setAdapter(xy);
				xy.notifyDataSetChanged();

				String str_result = _DeviceData.getM_hiPre() + ";" + _DeviceData.getM_lowPre() + ";"
						+ _DeviceData.getM_ml() + ";" + _DeviceData.getM_pjy() + ";"
						+ dateFormat.format(_DeviceData.getmSaveDate());
				String buffer_kt[] = str_result.split(";");
				UUID uuidJMRXueYa_kt = UUID.randomUUID();
				String dateJMRXueYa_kt = buffer_kt[4].toString();
				// 存高压
				if (NovaApplication.fdbmanger
						.findAllByWhere(SBCL_DATA.class,
								"IDCARD = '" + IDCARD + "' AND CL_TIME = '" + dateJMRXueYa_kt + "' AND CL_TYPE = '高压'")
						.size() <= 0) {
					saveCLData("康泰血压计08A-BT", "血压计", "高压", buffer_kt[0].toString() + "mmHg", "高压",
							uuidJMRXueYa_kt.toString(), IDCARD, dateJMRXueYa_kt);
				}

				// 存低压
				if (NovaApplication.fdbmanger
						.findAllByWhere(SBCL_DATA.class,
								"IDCARD = '" + IDCARD + "' AND CL_TIME = '" + dateJMRXueYa_kt + "' AND CL_TYPE = '低压'")
						.size() <= 0) {
					saveCLData("康泰血压计08A-BT", "血压计", "低压", buffer_kt[1].toString() + "mmHg", "低压",
							uuidJMRXueYa_kt.toString(), IDCARD, dateJMRXueYa_kt);
				}
				// 存脉率
				if (NovaApplication.fdbmanger
						.findAllByWhere(SBCL_DATA.class,
								"IDCARD = '" + IDCARD + "' AND CL_TIME = '" + dateJMRXueYa_kt + "' AND CL_TYPE = '脉率'")
						.size() <= 0) {
					saveCLData("康泰血压计08A-BT", "血压计", "脉率", buffer_kt[2].toString() + "次/分", "脉率",
							uuidJMRXueYa_kt.toString(), IDCARD, dateJMRXueYa_kt);
				}
				// 存平均压
				if (NovaApplication.fdbmanger
						.findAllByWhere(SBCL_DATA.class,
								"IDCARD = '" + IDCARD + "' AND CL_TIME = '" + dateJMRXueYa_kt + "' AND CL_TYPE = '平均压'")
						.size() <= 0) {
					saveCLData("康泰血压计08A-BT", "血压计", "平均压", buffer_kt[3].toString() + "mmHg", "平均压",
							uuidJMRXueYa_kt.toString(), IDCARD, dateJMRXueYa_kt);
				}
				System.out.println("保存血压");

			}
		} else {
			int size_xueyang = DeviceDataXueYang.m_deviceDataList_XueYang.size();
			if (size_xueyang > 0) {
				DeviceDataXueYang _deviceDataXueYang = DeviceDataXueYang.m_deviceDataList_XueYang.get(size_xueyang - 1);
				List<DeviceDataXueYang> listXueYang = new ArrayList<DeviceDataXueYang>();
				listXueYang.add(_deviceDataXueYang);
				xYang = new XueYangAdapter(KTXYJActivity.this, listXueYang);
				lv_list.setAdapter(xYang);
				xYang.notifyDataSetChanged();
				String str_result = _deviceDataXueYang.getXueYang() + ";" + _deviceDataXueYang.getMaiLv() + ";"
						+ dateFormat.format(_deviceDataXueYang.getmSaveDate());
				String buffer_kt[] = str_result.split(";");
				UUID uuidJMRXueYa_kt = UUID.randomUUID();
				String dateJMRXueYa_kt = buffer_kt[2].toString();
				// 存血氧
				if (NovaApplication.fdbmanger
						.findAllByWhere(SBCL_DATA.class,
								"IDCARD = '" + IDCARD + "' AND CL_TIME = '" + dateJMRXueYa_kt + "' AND CL_TYPE = '血氧'")
						.size() <= 0) {
					saveCLData("康泰血压计08A-BT", "血压计", "血氧", buffer_kt[0].toString() + "%", "血氧",
							uuidJMRXueYa_kt.toString(), IDCARD, dateJMRXueYa_kt);
				}
				// 存脉率
				if (NovaApplication.fdbmanger
						.findAllByWhere(SBCL_DATA.class,
								"IDCARD = '" + IDCARD + "' AND CL_TIME = '" + dateJMRXueYa_kt + "' AND CL_TYPE = '脉率'")
						.size() <= 0) {
					saveCLData("康泰血压计08A-BT", "血压计", "脉率", buffer_kt[1].toString() + "次/分", "脉率",
							uuidJMRXueYa_kt.toString(), IDCARD, dateJMRXueYa_kt);
				}
			}

		}

	}

	public void saveCLData(String device_name, String device_type, String cl_type, String cl_value, String cl_type_name,
			String GUID, String IDCARD, String cl_time) {
		SBCL_DATA sbcl_Data = new SBCL_DATA();
		sbcl_Data.setDEVICE_NAME(device_name);
		sbcl_Data.setDEVICE_TYPE(device_type);
		sbcl_Data.setCL_TYPE(cl_type);
		sbcl_Data.setCL_VALUE(cl_value);
		sbcl_Data.setCL_TYPE_NAME(cl_type_name);
		sbcl_Data.setGUID(GUID);
		sbcl_Data.setIDCARD(IDCARD);
		sbcl_Data.setCL_TIME(cl_time);
		sbcl_Data.setIS_UPDATE("Y");
		NovaApplication.fdbmanger.save(sbcl_Data);
	}

}